package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.testpaper.*;
import com.tanhua.model.vo.SoulOptionsVo;
import com.tanhua.model.vo.SoulPaperVo;
import com.tanhua.model.vo.SoulQuestionsVo;
import com.tanhua.model.vo.SoulReportVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TestSoulService {

    @DubboReference
    private SoulPaperApi soulPaperApi;
    @DubboReference
    private SoulAppraiseApi soulAppraiseApi;
    @DubboReference
    private SoulQuestionsApi soulQuestionsApi;
    @DubboReference
    private SoulOptionsApi soulOptionsApi;
    @DubboReference
    private SoulReportApi soulReportApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 查询试卷列表
     *
     * @return
     */
    public List<SoulPaperVo> testSoul() {
        List<SoulPaper> list = soulPaperApi.findAll();
        log.info("--------------{}", list);
        //获取试卷id
        List<Long> soulPaperIds = list.stream().map(item -> item.getId()).collect(Collectors.toList());
        log.info(soulPaperIds.toString());
        //获取题目
//        List<SoulQuestions> soulQuestions = soulQuestionsApi.findBySoulPaperIds(soulPaperIds);
        List<SoulQuestions> soulQuestions = soulQuestionsApi.findAll();
        log.info("题目{}", soulQuestions.toString());
        //获取题目id
        List<Long> soulQuestionsIds = soulQuestions.stream().map(item -> item.getId()).collect(Collectors.toList());
        log.info(soulQuestionsIds.toString());
        //获取答案选项
//        List<SoulOptions> soulOptions = soulOptionsApi.findByQuestionsIds(soulQuestionsIds);
        List<SoulOptions> soulOptions = soulOptionsApi.findAll();
        log.info("答案选项{}", soulOptions.toString());
        //封装vo
        Map<Long, List<SoulQuestionsVo>> map = encapsulationVo(soulQuestions, soulOptions);
        log.info("题目汇总{}", map.toString());
        //查询当前用户是否有报告
        List<SoulReport> soulReports = soulReportApi.findByUserId(UserHolder.getUserId());
        List<SoulPaperVo> soulPaperVos = new ArrayList<>();
        for (SoulPaper soulPaper : list) {
            Long id = soulPaper.getId();
            SoulPaperVo soulPaperVo = new SoulPaperVo();
            for (SoulReport soulReport : soulReports) {
                Long paperId = soulReport.getPaperId();
                if (paperId == 1&&("中级").equals(soulPaper.getLevel())) {
                        soulPaperVo.setIsLock(0);
                }
                if (paperId == 2&&("高级").equals(soulPaper.getLevel())) {
                        soulPaperVo.setIsLock(0);
                }
            }
            //遍历报告看是否解锁中级和高级
            if (("初级").equals(soulPaper.getLevel())) {
                soulPaperVo.setIsLock(0);
            }
            BeanUtils.copyProperties(soulPaper, soulPaperVo);
            soulPaperVo.setId(soulPaper.getId().toString());
            List<SoulQuestionsVo> soulQuestionsVos = map.get(id);
            soulPaperVo.setQuestions(soulQuestionsVos);
            soulPaperVos.add(soulPaperVo);
        }
        return soulPaperVos;
    }

    //传入题目id和答案封装答案vo和题目vo
    private Map<Long, List<SoulQuestionsVo>> encapsulationVo(List<SoulQuestions> soulQuestions, List<SoulOptions> soulOptions) {
        //收集SoulOptionsVo
        Map<Long, List<SoulOptionsVo>> map = new HashMap<>();
        for (SoulOptions soulOption : soulOptions) {
            if (soulOption != null) {
                Long questionsId = soulOption.getQuestionsId();
                //没有就添加，有就更新
                if (map.containsKey(questionsId)) {
                    List<SoulOptionsVo> soulOptionsVos = map.get(questionsId);
                    soulOptionsVos.add(SoulOptionsVo.init(soulOption));
                    map.put(questionsId, soulOptionsVos);
                } else {
                    List<SoulOptionsVo> list = new ArrayList<>();
                    list.add(SoulOptionsVo.init(soulOption));
                    map.put(questionsId, list);
                }
            }
        }
        //收集SoulQuestionsVo
        Map<Long, List<SoulQuestionsVo>> listMap = new HashMap<>();
        for (SoulQuestions soulQuestion : soulQuestions) {
            if (soulQuestion != null) {
                Long paperId = soulQuestion.getPaperId();
                //没有就添加，有就更新
                if (listMap.containsKey(paperId)) {
                    List<SoulQuestionsVo> list = listMap.get(paperId);
                    SoulQuestionsVo soulQuestionsVo = new SoulQuestionsVo();
                    soulQuestionsVo.setId(soulQuestion.getId().toString());
                    soulQuestionsVo.setQuestion(soulQuestion.getQuestion());
                    soulQuestionsVo.setOptions(map.get(soulQuestion.getId()));
                    list.add(soulQuestionsVo);
                    listMap.put(paperId, list);
                } else {
                    List<SoulQuestionsVo> list = new ArrayList<>();
                    SoulQuestionsVo soulQuestionsVo = new SoulQuestionsVo();
                    soulQuestionsVo.setId(soulQuestion.getId().toString());
                    soulQuestionsVo.setQuestion(soulQuestion.getQuestion());
                    soulQuestionsVo.setOptions(map.get(soulQuestion.getId()));
                    list.add(soulQuestionsVo);
                    listMap.put(paperId, list);
                }
            }
        }
        return listMap;
    }

    //提交问卷
    public String postTestSoul(List<Map> answers) {
        //根据题目和选项获取分数
        Double score = 0.0;
        for (Map answer : answers) {
            Long questionId = Long.valueOf(answer.get("questionId").toString());
            Long optionId = Long.valueOf(answer.get("optionId").toString());
            Double s = soulOptionsApi.findScore(questionId, optionId);
            score = s + score;
        }
        //传递分数查询属于那个级别
        log.info("分数{}", score);
        SoulAppraise soulAppraise = soulAppraiseApi.findTitle(score);
        log.info("性格类型{}", soulAppraise);
        //保存性格并获取报告id，获取用户详细信息
        UserInfo byId = userInfoApi.findById(UserHolder.getUserId());
        SoulReport soulReport = new SoulReport(soulAppraise, byId, score);
        Long questionId = Long.valueOf(answers.get(0).get("questionId").toString());
        if (questionId >= 1 && questionId <= 5) {
            soulReport.setPaperId(1l);
        } else if (questionId >= 6 && questionId <= 10) {
            soulReport.setPaperId(2l);
        } else {
            soulReport.setPaperId(3l);
        }
        soulReport.setTitle(soulAppraise.getTitle());
        soulReport.setContent(soulAppraise.getContent());
        soulReport.setDimensions(soulAppraise.getDimensions());
        soulReportApi.save(soulReport);
        String id = soulReportApi.findByObject(soulReport);

        return id;
    }

    //查看问卷
    public SoulReportVo report(Long id) {
        SoulReport soulReport = soulReportApi.findById(id);
        //获取属性
        List<Long> userIds =  soulReportApi
                .findbyAppraiseId(soulReport.getAppraiseId(),soulReport.getPaperId(),UserHolder.getUserId());

        List<UserInfo> list = new ArrayList<>();
        if(CollUtil.isNotEmpty(userIds)) {
            //查询用户详情
            Map<Long, UserInfo> map = userInfoApi.findByIds(userIds,null);
            //转化list
            list = map.values().stream().collect(Collectors.toList());
        }
        //构造返回
        return SoulReportVo.init(soulReport,list);
    }
}
